package com.kitty.game.fixed.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kitty.common.utils.SpringUtils;
import com.kitty.game.fixed.entity.FixedTeam;
import com.kitty.game.fixed.message.FixedTeamData;
import com.kitty.game.fixed.message.FixedTeamDataMembers;
import com.kitty.game.fixed.message.FixedTeamOneKey;
import com.kitty.game.role.model.Role;
import com.kitty.game.team.service.NewTeamService;
import com.kitty.game.team.service.TeamService;
import com.kitty.mina.cache.SessionUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.mina.core.session.IoSession;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class UseFixedTeamService {
    @Autowired
    TeamService teamService;
    @Autowired
    NewTeamService newTeamService;
    @Autowired
    Dao dao;
    /**
     * 邀请进入固定队，如果gid为空表示一键邀请
     * @param session
     * @param fixedTeamOneKey
     */
    //逻辑好像不对。 一键组队。的意思好像是 自己有队伍就邀请他人，自己没队伍就加入他人队伍
    public void inviteTeam(IoSession session, FixedTeamOneKey fixedTeamOneKey){
        String gid = fixedTeamOneKey.getGid();
        Role role = SessionUtils.getRoleBySession(session);

        if(StringUtils.isEmpty(gid)){
            FixedTeamData fixedTeamData = new FixedTeamData();
            List<FixedTeam> fixedList = dao.query(FixedTeam.class, Cnd.where("uid", "=", role.getFixedTeam()));
            FixedTeam fixedTeam = new FixedTeam();
            if(fixedList.size()>0){
                fixedTeam = fixedList.get(0);
                JSONArray parseArray = JSONObject.parseArray(fixedTeam.getMembers());
                for (int i = 0; i < parseArray.size(); i++) {
                    JSONObject jsonObject = parseArray.getJSONObject(i);
                    int roleId = Integer.parseInt(jsonObject.getString("gid"));
                    if(role.getRoleId() != roleId){
                        FixedTeamDataMembers m = new FixedTeamDataMembers();
                        Role teamRole = SpringUtils.getRoleService().getOnlinePlayer(roleId);
                        if(teamRole != null){
                            newTeamService.inviteJoinTeam(role,teamRole.getRoleId());
                        }
                    }
                }
            }
        }else{
            newTeamService.inviteJoinTeam(role,Integer.parseInt(gid));
        }
    }

}
